import { login, getUserInfo, logout } from "@/api/cloudbase-login";
import FingerprintJS from "@fingerprintjs/fingerprintjs";
import router from "@/router/index";
import store from "store";
export const FINGERPRINT_LOCAL_NAME = "fingerprintId";
const fingerprintId = store.get(FINGERPRINT_LOCAL_NAME);
const state = {
  user: {},
};
const mutations = {
  SET_USER: (state, user) => {
    Object.assign(state.user, user);
  },
  SET_LOGINTYPE: (state, loginType) => {
    state.loginType = loginType;
  },
  SET_LOGIN_STATE: (state, data) => {
    Object.assign(state.user, data.user);
    state.loginType = data.loginType;
  },
};

const actions = {
  async login({ commit, dispatch, state }, payload) {
    try {
      const res = await login(payload);
      if (res && res.code == 200) {
        store.set("token", res.token);
        await dispatch("getUserInfo");
        return Promise.resolve(res);
      }
      return Promise.reject(res);
    } catch (error) {
      return Promise.reject(error);
    }
  },
  async getUserInfo({ commit }) {
    const token = store.get("token");
    if (!token) {
      return Promise.reject("token is null");
    }
    if (state.user.userId) {
      return Promise.resolve(state.user);
    }
    const res = await getUserInfo();
    if (res && res.code == 200) {
      commit("SET_USER", res.user);
      return Promise.resolve(res.user);
    }
    return Promise.reject(res);
  },

  async getFingerprint({ commit, state }) {
    return new Promise(async (resolve, reject) => {
      if (state.user.fingerprintId) {
        resolve(state.user.fingerprintId);
        return;
      }
      if (fingerprintId) {
        resolve(fingerprintId);
        commit("SET_USER", { fingerprintId: fingerprintId });
        return;
      }
      const fp = await FingerprintJS.load();
      const result = await fp.get();
      commit("SET_USER", { fingerprintId: result.visitorId });
      store.set(FINGERPRINT_LOCAL_NAME, result.visitorId);
      resolve(result.visitorId);
    });
  },
  async logout() {
    try {
      await logout();
      store.remove("token");
      router.replace("/");
    } catch (error) {}
  },
};
const getters = {
  GET_USER: () => {
    return state.user;
  },
  isLogin: () => () => (store.get("token") ? true : false),
  fingerprintId: () => state.user.fingerprintId,
  userId: () => state.user?.userId,
};
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};
